<?php
// +----------------------------------------------------------------------
// |MCPHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author jokerfei [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------
namespace addons\Alipay\controller;

require_once __DIR__ . '/../sdk/Aop/AopClient.php';
require_once __DIR__ . '/../sdk/Aop/request/AlipaySystemOauthTokenRequest.php';

/**
 * 支付宝用户授权接口
 */
class Authcode extends Base {

	/**
	 * alipay.system.oauth.token(换取授权访问令牌)
	 * @author mitu
	 * @date   2024-01-09
	 * @param  string     $authorizationCode 授权码
	 * @param  string     $grantType         用授权码来换取授权令牌: authorization_code
用刷新令牌来换取一个新的授权令牌: refresh_token
	 * @param  [type]     $refreshToken      刷新令牌，上次换取访问令牌时得到。本参数在 grant_type 为 authorization_code 时不填；为 refresh_token 时必填，且该值来源于此接口的返回值 app_refresh_token（即至少需要通过 grant_type=authorization_code 调用此接口一次才能获取）
	 * @return [type]                        [description]
	 */
	public function systemOauthToken($authorizationCode = '', $grantType = 'authorization_code', $refreshToken = null)
	{
		$privateKey = $this->config['private_key'];
		$alipayPublicKey = $this->config['public_key'];
		
		$alipayClient = new \AopClient();
		$alipayClient->gatewayUrl = "https://openapi.alipay.com/gateway.do";
		$alipayClient->appId = $this->config['appid'];
		$alipayClient->rsaPrivateKey = $privateKey;
		$alipayClient->format = "json";
		$alipayClient->alipayrsaPublicKey = $alipayPublicKey;
		$alipayClient->postCharset = "UTF-8";
		$alipayClient->signType = "RSA2";
		$alipayClient->apiVersion = '1.0';

		$request = new \AlipaySystemOauthTokenRequest();

		if ($authorizationCode) {
			$request->setCode($authorizationCode);
		}
		$request->setGrantType($grantType);
		if ($refreshToken) {
			$request->setRefreshToken($refreshToken);
		}
		$responseResult = $alipayClient->execute($request);

		$responseApiName = str_replace(".","_",$request->getApiMethodName())."_response";
		$response = $responseResult->$responseApiName;
		if (!$response) {
			$response = (array)$responseResult;
			if(!empty($response['error_response'])){
				$errorResponse = (array)$response['error_response'];
				throw new \Exception($errorResponse['sub_msg']);
			}
			\think\facade\Log::info('调取支付失败'.$e->getMessage());
			throw new \Exception('调取支付失败');
		}

		return $response;
	}

	/**
	 * AES密钥解密支付宝加密数据
	 * @author mitu
	 * @date   2024-01-09
	 * @param  [type]     $content base64加密数据
	 * @return [type]              json
	 */
	public function openSign($content) {
		//AES密钥
		$aesKey = $this->config['aes_key'];
	  	$result=openssl_decrypt(base64_decode($content), 'AES-128-CBC', base64_decode($aesKey),OPENSSL_RAW_DATA);
	  	return json_decode($result, true);
    }
}